from django.shortcuts import render, redirect
from django.utils import timezone
from .models import Employee, Shift
from .forms import EmployeeImportForm
from datetime import datetime, timedelta

def generate_schedule(request):
    if request.method == 'POST':
        try:
            start_date = datetime.strptime(request.POST['start_date'], '%Y-%m-%d').date()
            days = int(request.POST['days'])
            
            # 检查历史排班冲突
            if Shift.objects.filter(
                shift_date__range=(start_date, start_date + timedelta(days=days))
            ).exists():
                return render(request, 'generate.html', 
                            {'error': "所选日期范围存在已有排班记录"})
                
            employees = list(Employee.objects.all())
            if not employees:
                return redirect('admin:index')
            
            shifts = []
            for i in range(days):
                current_date = start_date + timedelta(days=i)
                for idx, employee in enumerate(employees):
                    shift_type = ['M', 'A', 'N'][idx % 3]
                    shifts.append(Shift(
                        employee=employee,
                        shift_type=shift_type,
                        shift_date=current_date
                    ))
            
            Shift.objects.bulk_create(shifts)
            return redirect('schedule')
            
        except ValueError:
            return render(request, 'generate.html', 
                        {'error': "请输入有效的日期格式(YYYY-MM-DD)和天数"})
    
    # 设置默认开始日期为明天
    initial = {'start_date': timezone.now().date() + timedelta(days=1)}
    return render(request, 'generate.html', initial)

def schedule_view(request):
    shifts = Shift.objects.all().order_by('shift_date')
    return render(request, 'schedule.html', {'shifts': shifts})

def import_employees(request):
    if request.method == 'POST':
        form = EmployeeImportForm(request.POST, request.FILES)
        if form.is_valid():
            try:
                form.process_file()
                return redirect('admin:scheduler_employee_changelist')
            except Exception as e:
                return render(request, 'import.html', {'form': form, 'error': str(e)})
    else:
        form = EmployeeImportForm()
    return render(request, 'import.html', {'form': form})